#include "RtspCapture.hpp"
#include <iostream>

RtspCapture::RtspCapture(const std::string& pipeline)
    : pipeline_(pipeline),
      last_retry_time_(std::chrono::steady_clock::now()
                       - std::chrono::seconds(10))
{
}

RtspCapture::~RtspCapture()
{
    stop();
}

bool RtspCapture::openRtsp()
{
    if (cap_.isOpened())
        cap_.release();

    std::cout << "[RtspCapture] 尝试打开 RTSP/GStreamer 管道..." << std::endl;
    cap_.open(pipeline_, cv::CAP_GSTREAMER);

    if (!cap_.isOpened())
    {
        std::cerr << "[RtspCapture] 打开失败" << std::endl;
        is_opened_ = false;
        return false;
    }

    std::cout << "[RtspCapture] 打开成功" << std::endl;
    is_opened_ = true;
    return true;
}

void RtspCapture::start()
{
    if (running_)
        return;

    running_ = true;
    capture_thread_ = std::thread(&RtspCapture::captureLoop, this);
}

void RtspCapture::stop()
{
    if (!running_)
        return;

    running_ = false;
    if (capture_thread_.joinable())
        capture_thread_.join();

    if (cap_.isOpened())
        cap_.release();
    is_opened_ = false;
}

bool RtspCapture::getFrame(cv::Mat& out_frame)
{
    std::lock_guard<std::mutex> lock(frame_mutex_);
    if (latest_frame_.empty())
        return false;

    latest_frame_.copyTo(out_frame);
    return true;
}

void RtspCapture::captureLoop()
{
    while (running_)
    {
        // 每秒重试一次打开 RTSP
        if (!cap_.isOpened())
        {
            auto now = std::chrono::steady_clock::now();
            auto dt  = std::chrono::duration_cast<std::chrono::seconds>(
                           now - last_retry_time_).count();

            if (dt >= 1)
            {
                last_retry_time_ = now;
                openRtsp();
            }

            // 睡一会儿，别疯狂空转
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            continue;
        }

        cv::Mat frame;
        bool ok = cap_.read(frame);
        if (!ok || frame.empty())
        {
            std::cerr << "[RtspCapture] 读取帧失败，将断开重连" << std::endl;
            cap_.release();
            is_opened_ = false;
            last_retry_time_ = std::chrono::steady_clock::now();
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            continue;
        }

        {
            std::lock_guard<std::mutex> lock(frame_mutex_);
            frame.copyTo(latest_frame_);
        }

        // 控制一下频率（根据需要可调）
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}
